<?php
namespace Icsoc\DataBundle\Model;

use Elasticsearch\Client;
use Doctrine\DBAL\DBALException;
use Icsoc\CoreBundle\Logger\ActionLogger;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * 下面中用到info参数的json格式大概为 ；filter搜素(具体提供搜素字段各个接口不一样)，
 *  pagination分页(rows 每页显示条数,page第几页)，sort排序
 *  {"pagination":{"rows":20,"page":"5"},"filter":{"endresult":"0"},"sort":{"field":"id","order":"desc"}}
 * Class BillModel
 * @package Icsoc\DataBundle\Model
 *
 */
class MonitorModel extends BaseModel
{

    /**
     * 呼叫类型
     * @var array
     */
    private $callType = array(
        '1' => '呼出',
        '2' => '呼入',
        '3' => '呼出转接',
        '4' => '呼入转接',
        '5' => '呼出拦截',
        '6' => '呼入拦截',
        '7' => '被咨询',
        '9' => '监听',
    );

    /**
     * 背景颜色
     * @var array
     */
    private $backgroudColor = array(
        "#FFF68F", "#FFEFD5", "#FFE4E1", "#FFDEAD", "#FFC1C1", "#FFB90F", "#FFA54F","#FF7F50", "#FF6EB4", "#FF4500",
        "#FF3030", "#F0FFFF", "#F0E68C", "#EEEE00","#EEAEEE", "#EE9A49", "#EE8262", "#EE7621", "#EE3A8C", "#EE00EE",
        "#9C9C9C", "#9AC0CD", "#98FB98", "#8E8E38", "#7CFC00", "#7171C6", "#00FA9A", "#0000EE","#BCEE68", "#C1FFC1",
        "#B8860B", "#B2DFEE", "#A0522D", "#8B0A50", "#8B2500","#4876FF", "#6E8B3D", "#708090", "#3CB371", "#EEA2AD",
        "#FAFAD2", "#FFBBFF",
    );

    /** @var \Symfony\Component\DependencyInjection\Container */
    public $container;

    /** @var \Doctrine\DBAL\Connection */
    private $dbal;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->dbal = $this->container->get('doctrine.dbal.default_connection');
    }


    /**
     * 获取坐席监控数据
     * @param array $param 参数 格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         user_ids,//坐席id，多个坐席 "," (逗号)隔开(eg: 1,2,3)
     *                         que_id, //技能组id,
     *                         info, //搜素分页相关信息,
     *                     )
     * @return array
     */
    public function agentMonitor(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $user_ids = empty($param['user_ids']) ? 0 : $param['user_ids'];
        $que_id = empty($param['que_id']) ? 0 : $param['que_id'];
        $infos = empty($param['info']) ? '' : $this->purifyHtml($param['info']);
        $agStatus = $this->container->getParameter("ag_status");
        /** @var array $msg 验证vcc_code是否正确 */
        $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        //分页搜索相关信息；
        $info = array();
        if (!empty($infos)) {
            $info = json_decode($infos, true);
            if (json_last_error()) {
                return array('code' => 405, 'message' => 'info格式非json');
            }
        }
        /*
        if (empty($user_ids)) {
            $ret = array(
                'code' => 405,
                'message' => '坐席ID为空',
            );
            return new JsonResponse($ret);
        }*/
        $user_arr = array();
        if (!empty($user_ids)) {
            $user_arr = explode(",", $user_ids);
            foreach ($user_arr as $val) {
                if (!is_numeric($val)) {
                    $ret = array(
                        'code' => 403,
                        'message' => '坐席ID中含有非数字项',
                    );
                    return $ret;
                }
            }
        }

        if (!empty($que_id)) {
            if (!is_numeric($que_id)) {
                $ret = array(
                    'code' => 404,
                    'message' => '技能组ID包含非数字字符',
                );
                return $ret;
            }
            //通过技能组ID获得 坐席ID；
            $list = $this->dbal->fetchAll(
                "SELECT ag_id FROM win_agqu WHERE que_id = :que_id",
                array('que_id' => $que_id)
            );
            if (empty($list)) {
                $user_arr [] = 0;
            } else {
                foreach ($list as $value) {
                    $user_arr[] = $value['ag_id'];
                }
            }
        }
        $str = implode(',', array_unique($user_arr));
        $where = !empty($user_arr) ? " AND ag_id IN ($str) " : '';
        //获得技能组；
        $que_list = $this->dbal->fetchAll(
            'SELECT a.que_id,q.que_name,a.ag_id ' .
            'FROM win_agqu as a LEFT JOIN win_queue as q ON a.que_id = q.id ' .
            'WHERE 1 ' . $where
        );
        $que_row = $que_ag = array();
        if (!empty($que_list)) {
            foreach ($que_list as $v) {
                $que_row[$v['que_id']] = $v['que_name'];
                $que_ag[$v['ag_id']][] = $v['que_name']; //所属技能组
            }
        }
        //处理搜索和排序条件
        if (isset($info['filter'])) {
            if (isset($info['filter']['keyword']) && !empty($info['filter']['keyword'])) {
                $keyword = $info['filter']['keyword'];
                $where .= " AND (ag_num  LIKE '%" . $keyword . "%'
                     OR pho_num LIKE '%" . $keyword . "%' OR ag_name LIKE '%" . $keyword . "%') ";
            }
        }
        $count = $this->dbal->fetchColumn(
            'SELECT count(*) ' .
            'FROM win_agmonitor ' .
            'WHERE vcc_id = :vid ' . $where,
            array('vid' => $vcc_id)
        );
        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'win_agmonitor', $info);
        $now_data = $this->dbal->fetchAll(
            "SELECT ag_id,pho_num,ag_sta,ag_sta_time,UNIX_TIMESTAMP(now()) AS now,UNIX_TIMESTAMP(CURDATE()) AS today,".
            'ag_num,ag_name,ag_sta_reason,pho_id,pho_num,pho_sta,pho_sta_reason,login_ip,time_firlogin,time_login,' .
            'time_lastcall,secs_login,secs_ready,secs_busy,secs_call,secs_ring,secs_wait,times_call,times_busy,'.
            'pho_sta_time,pho_sta_callque,pho_sta_calltype ' .
            " FROM win_agmonitor WHERE vcc_id = :vcc_id " . $where .
            'ORDER BY ' . $page['sort'] . ' ' . $page['order'] . ' LIMIT ' . $page['start'] . ',' . $page['limit'],
            array('vcc_id' => $vcc_id)
        );
        $result = $temp = array();
        foreach ($now_data as $v) {
            /* 坐席 'ag_id'*/
            $temp['ag_id'] = $v['ag_id'];
            /* 坐席分机号码 'pho_num'*/
            $temp['pho_num'] = $v['pho_num'];
            /*坐席状态状态 'status'*/
            $temp['ag_sta'] = $v['ag_sta'];
            /* 状态持续时长 'status_secs'*/
            $temp['status_secs'] = $v['now'] - ($v['ag_sta_time'] >= $v['today'] ? $v['ag_sta_time'] : $v['today']);
            $temp['ag_num'] = $v['ag_num'];
            $temp['ag_name'] = $v['ag_name'];
            $temp['ag_sta_reason'] = $v['ag_sta_reason'];
            $temp['pho_id'] = $v['pho_id'];
            $temp['pho_num'] = $v['pho_num'];
            $temp['pho_sta'] = $v['pho_sta'];
            $temp['pho_sta_reason'] = $v['pho_sta_reason'];
            $temp['login_ip'] = $v['login_ip'];
            $temp['time_firlogin'] = date('Y-m-d H:i:s', $v['time_firlogin']);
            $temp['time_login'] = $v['time_login'];
            $temp['time_lastcall'] = $v['time_lastcall'];
            if (!empty($que_ag['ag_id'])) {
                sort($que_ag[$v['ag_id']]);//防止没有技能组的坐席出现；导致错误的发生
            }
            $temp['all_que_name'] = isset($que_ag[$v['ag_id']]) ? implode(',', $que_ag[$v['ag_id']]) : '';
            if (isset($que_ag[$v['ag_id']])) {
                $temp['que_name'] = count($que_ag[$v['ag_id']]) > 3
                    ? $que_ag[$v['ag_id']][0] . "," . $que_ag[$v['ag_id']][1] . "," . $que_ag[$v['ag_id']][2] . ",..." :
                    implode(',', $que_ag[$v['ag_id']]);
            } else {
                $temp['que_name'] = '';
            }
            //占用状态；
            if ($v['ag_sta'] == 4) {
                if ($v['pho_sta'] == 1) {
                    $temp['status'] = "振铃";
                } elseif ($v['pho_sta'] == 2) {
                    $temp['status'] = "通话";
                }
            } else {
                $temp['status'] = $agStatus[$v['ag_sta']];
            }
            /*登陆时长*/
            $temp['secs_login'] = $v['now'] - ($v['time_login'] >= $v['today'] ? $v['time_login'] : $v['today']) + $v['secs_login'];
            /*就绪时长*/
            if ($v['ag_sta'] == 1) {
                $temp['secs_ready'] = $v['now'] - ($v['ag_sta_time'] >= $v['today'] ? $v['ag_sta_time'] : $v['today']) + $v['secs_ready'];
            } else {
                $temp['secs_ready'] = $v['secs_ready'];
            }
            /*置忙时长*/
            if ($v['ag_sta'] == 2) {
                $temp['secs_busy'] = $v['now'] - ($v['ag_sta_time'] >= $v['today'] ? $v['ag_sta_time'] : $v['today']) + $v['secs_busy'];
            } else {
                $temp['secs_busy'] = $v['secs_busy'];
            }
            /*通话时长*/
            if ($v['pho_sta'] == 2) {
                $temp['secs_call'] = $v['now'] - ($v['pho_sta_time'] >= $v['today'] ? $v['pho_sta_time'] : $v['today']) + $v['secs_call'];
            } else {
                $temp['secs_call'] = $v['secs_call'];
            }
            /* 振铃时长 */
            if ($v['pho_sta'] == 1) {
                $temp['secs_ring'] = $v['now'] - ($v['pho_sta_time'] >= $v['today'] ? $v['pho_sta_time'] : $v['today']) + $v['secs_ring'];
            } else {
                $temp['secs_ring'] = $v['secs_ring'];
            }
            /* 整理时长 */
            if ($v['ag_sta'] == 5) {
                $temp['secs_wait'] = $v['now'] - ($v['ag_sta_time'] >= $v['today'] ? $v['ag_sta_time'] : $v['today']) + $v['secs_wait'];
            } else {
                $temp['secs_wait'] = $v['secs_wait'];
            }
            $temp['times_call'] = $v['times_call'];
            $temp['times_busy'] = $v['times_busy'];
            $temp['pho_sta_calltype'] = isset($this->callType[$v['pho_sta_calltype']]) ?
                $this->callType[$v['pho_sta_calltype']] : '';
            $temp['pho_sta_callque'] = isset($que_row[$v['pho_sta_callque']]) ? $que_row[$v['pho_sta_callque']] : '';
            $result[] = $temp;
        }
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'page' => $page['page'],
            'totalPage' => $page['totalPage'],
            'data' => $result,
        );
        return $ret;
    }

    /**
     * 获取技能组监控数据
     * @param array $param 参数格式为 array(
     *                              vcc_code,//企业代码
     *                              que_ids,//技能组id,多个用","逗号隔开(1,2,3)
     *                          )
     * @return array
     */
    public function queueMonitor(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $que_ids = empty($param['que_ids']) ? 0 : $param['que_ids'];
        /** @var array $msg 验证vcc_code是否正确 */
        $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        if (!empty($que_ids)) {
            $que_arr = explode(",", $que_ids);
            foreach ($que_arr as $val) {
                if (!is_numeric($val)) {
                    $ret = array(
                        'code' => 403,
                        'message' => '技能组ID中含有非数字项',
                    );
                    return $ret;
                }
            }
        } else {
            //如果不传就是所有的技能组
            $que_row = $this->dbal->fetchAll(
                'SELECT id ' .
                'FROM win_queue ' .
                'WHERE vcc_id = :vcc_id AND is_del = 0 ',
                array('vcc_id' => $vcc_id)
            );
            $que_list = array();
            if (!empty($que_row)) {
                foreach ($que_row as $v) {
                    $que_list[] = $v['id'];
                }
            }
            $que_ids = !empty($que_list) ? implode(',', $que_list) : '0';
        }

        $call_queue = $this->dbal->fetchAll(
            "SELECT que_id,COUNT(*) AS total FROM win_call_queue WHERE vcc_id = :vcc_id " .
            " AND que_id IN ($que_ids) GROUP BY que_id",
            array('vcc_id' => $vcc_id)
        );
        $new_call_queue = array();
        foreach ($call_queue as $cvalue) {
            $new_call_queue[$cvalue['que_id']] = $cvalue;
        }
        $result_other = $this->dbal->fetchAll(
            "SELECT ag_id,ag_sta,pho_sta,pho_sta_callque FROM win_agmonitor WHERE vcc_id = :vcc_id",
            array('vcc_id' => $vcc_id)
        );
        $new_result_other = array();
        foreach ($result_other as $rvalue) {
            $new_result_other[$rvalue['ag_id']] = $rvalue;
        }
        $que_row = $this->dbal->fetchAll(
            "SELECT q.id as que_id,a.ag_id,q.que_name
            FROM win_agqu a RIGHT JOIN win_queue q ON a.que_id = q.id WHERE q.id IN ($que_ids)"
        );
        $queue_agent = $queInfo = array();
        if (!empty($que_row)) {
            foreach ($que_row as $value) {
                $queue_agent[$value["que_id"]][] = $value["ag_id"];
                $queInfo[$value['que_id']] = $value['que_name'];
            }
        }

        //处理数据
        $result = array();
        $data = array();
        foreach ($queue_agent as $queue_id => $agent_ids) {
            $result['que_id'] = $queue_id;
            $result['que_name'] = $queInfo[$queue_id];
            $result['online'] = 0;//在线
            $result['queue'] = 0;//排队
            $result['ring'] = 0;//振铃
            $result['call'] = 0;//通话
            $result['rest'] = 0;//事后处理
            $result['ready'] = 0;//就绪
            $result['busy'] = 0;//置忙

            /* 排队 */
            if (!empty($new_call_queue[$queue_id]["total"])) {
                $result['queue'] = $new_call_queue[$queue_id]["total"];
            }

            foreach ($new_result_other as $ag_id => $other) {
                /* 判断该坐席是否在该队列中 */
                if (in_array($ag_id, $agent_ids)) {
                    /* 在线 */
                    if ($other['ag_sta'] != 0) {
                        $result['online']++;
                    }
                    /* 振铃 根据进入的技能组来判断 */
                    if ($other['ag_sta'] == 4 && $other['pho_sta'] == 1 && $queue_id == $other['pho_sta_callque']) {
                        $result['ring']++;
                    }
                    /* 通话 根据进入的技能组来判断 */
                    if ($other['ag_sta'] == 4 && $other['pho_sta'] == 2 && $queue_id == $other['pho_sta_callque']) {
                        $result['call']++;
                    }
                    /* 事后处理 */
                    if ($other['ag_sta'] == 5) {
                        $result['rest']++;
                    }
                    /* 就绪 */
                    if ($other['ag_sta'] == 1) {
                        $result['ready']++;
                    }
                    /* 置忙 */
                    if ($other['ag_sta'] == 2) {
                        $result['busy']++;
                    }
                }
            }

            $data[] = $result;
        }

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $data,
        );
        return $ret;
    }

    /**
     * 获取排队监控数据
     * @param array $param 参数格式为 array(
     *                              vcc_code,//企业代码
     *                              que_id,//技能组id
     *                          )
     * @return array
     */
    public function callsMonitor(array $param)
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $que_id = empty($param['que_id']) ? 0 : $param['que_id'];

        /** @var array $msg 验证vcc_code是否正确 */
        $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $where = '';
        if (!empty($que_id)) {
            if (!is_numeric($que_id)) {
                $ret = array(
                    'code' => 403,
                    'message' => '技能组ID包含非数字字符',
                );
                return $ret;
            }
            $where = "AND que_id = '$que_id'";
        }

        $list = $this->dbal->fetchAll(
            "SELECT *,UNIX_TIMESTAMP(now()) AS now FROM win_call_queue WHERE vcc_id = :vcc_id $where",
            array('vcc_id' => $vcc_id)
        );
        $result = $data = array();
        foreach ($list as $v) {
            /* 队列ID que_id*/
            $result['que_id'] = $v['que_id'];
            /* 主叫号码 queuer_num*/
            $result['queuer_num'] = $v['queuer_num'];
            /* 进入队列时间 in_time*/
            $result['in_time'] = $v['in_time'];
            /* 排队状态 queuer_sta*/
            $result['queuer_sta'] = $v['queuer_sta'];
            /* 排队时长 in_secs*/
            $result['in_secs'] = $v['now'] - $v['in_time'];
            $result['que_name'] = $v['que_name'];
            $data[] = $result;
        }
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $data,
        );
        return $ret;
    }

    /**
     * 获取坐席统计数据接口
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         user_ids,//坐席id,多个用","逗号隔开(1,2,3)
     *                         start_date,//开始时间，YY-MM-DD
     *                         end_date,//结束时间， YY-MM-DD
     *                     )
     * @return array
     */
    public function stadataMonitor(array $param)
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $user_ids = empty($param['user_ids']) ? 0 : $param['user_ids'];
        $start_date = empty($param['start_date']) ? 0 : $param['start_date'];
        $end_date = empty($param['end_date']) ? 0 : $param['end_date'];

        /** @var array $msg 验证vcc_code是否正确 */
        $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($user_ids)) {
            $ret = array(
                'code' => 403,
                'message' => '用户ID为空',
            );
            return $ret;
        }
        $user_arr = explode(",", $user_ids);
        foreach ($user_arr as $val) {
            if (!is_numeric($val)) {
                $ret = array(
                    'code' => 404,
                    'message' => '用户ID中含有非数字项',
                );
                return $ret;
            }
        }

        //验证开始日期格式是否正确
        $msg = $this->container->get('icsoc_data.helper')->isDate('开始日期格式不正确', $start_date, 405);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        //验证结束日期格式是否正确
        $msg = $this->container->get('icsoc_data.helper')->isDate('结束日期格式不正确', $end_date, 406);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $data = $this->dbal->fetchAll(
            "SELECT ag_id,login_secs,ready_secs,busy_secs FROM rep_agent_day WHERE vcc_id = :vcc_id " .
            " AND ag_id IN ($user_ids) AND nowdate <= :end_date AND nowdate >= :start_date ",
            array('vcc_id' => $vcc_id, 'end_date' => $end_date, 'start_date' => $start_date)
        );
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $data,
        );
        return $ret;
    }

    /**
     * 获取坐席操作明细数据接口
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         info,//提供搜素的字段有 ag_num 坐席工号 ag_name 坐席姓名
     *                              //开始时间: start_time(YYYY-MM-DD HH:II:SS)
     *                              //结束时间: end_time(YYYY-MM-DD HH:II:SS)
     *                              //操 作: ag_sta_type (1：登陆，2：示忙)
     *                     )
     * @return array|string
     */
    public function detaildataMonitor(array $param)
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $info = empty($param['info']) ? 0 : $param['info'];

        //验证vcc_code;
        $msg = $vcc_id = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message' => 'info格式非json');
            }
        }

        $where = '';
        $params = array();
        if (isset($addInfo['filter'])) {
            //坐席工号；
            $where .= isset($addInfo['filter']['ag_num']) && !empty($addInfo['filter']['ag_num']) ?
                " AND ag_num LIKE '%" . $addInfo['filter']['ag_num'] . "%' " : '';

            //操作，登陆，示忙；
            if (isset($addInfo['filter']['ag_sta_type']) && $addInfo['filter']['ag_sta_type'] !== '') {
                $ag_sta_type = $addInfo['filter']['ag_sta_type'];
                $where .= " AND ag_sta_type = :ag_sta_type ";
                $params['ag_sta_type'] = (int)$ag_sta_type;
            }

            //坐席姓名；
            $where .= isset($addInfo['filter']['ag_name']) && !empty($addInfo['filter']['ag_name']) ?
                " AND ag_name LIKE '%" . $addInfo['filter']['ag_name'] . "%' " : '';

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $start_time = $addInfo['filter']['start_time'];
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('开始时间格式不正确', $start_time, 404);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where .= "AND start_time >= UNIX_TIMESTAMP('$start_time')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $end_time = $addInfo['filter']['end_time'];
                $msg = $this->container->get('icsoc_data.helper')->isDateTime('结束时间格式不正确', $end_time, 405);
                if (!empty($msg) && is_array($msg)) {
                    return $msg;
                }
                $where .= "AND start_time <= UNIX_TIMESTAMP('$end_time')";
            }
        }
        $params['vcc_id'] = $vcc_id;
        $count = $this->dbal->fetchColumn(
            'SELECT count(*) ' .
            'FROM win_agsta_detail ' .
            'WHERE vcc_id = :vcc_id ' . $where,
            $params
        );
        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'win_agsta_detail', $addInfo);
        $data = $this->dbal->fetchAll(
            "SELECT vcc_id,ag_id,ag_name,ag_sta_type,start_time,duration,ag_sta_reason,ag_login_ip,ag_num,bend " .
            "FROM win_agsta_detail " .
            'WHERE vcc_id = :vcc_id ' . $where .
            'ORDER BY ' . $page['sort'] . ' ' . $page['order'] . ' LIMIT ' . $page['start'] . ',' . $page['limit'],
            $params
        );
        //查看原因
        $reason_list = $this->dbal->fetchAll(
            "SELECT id,stat_reason FROM win_agstat_reason ",
            array('vcc_id' => $vcc_id)
        );
        $reason_detail = array();
        foreach ($reason_list as $v) {
            $reason_detail[$v['id']] = $v['stat_reason'];
        }
        $new_data = $temp = array();
        foreach ($data as $v) {
            $temp['vcc_id'] = $v['vcc_id'];
            $temp['ag_id'] = $v['ag_id'];
            $temp['ag_name'] = $v['ag_name'];
            $temp['ag_num'] = $v['ag_num'];
            $temp['ag_sta_type'] = $v['ag_sta_type'] == 1 ? '登录' : '示忙';
            $temp['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            $temp['duration'] = $v['duration'];
            $temp['ag_login_ip'] = $v['ag_login_ip'];
            $temp['bend'] = $v['bend'] ? '结束' : '';
            $temp['ag_sta_reason'] = isset($reason_detail[$v['ag_sta_reason']]) && $v['ag_sta_type'] != 1
                ? $reason_detail[$v['ag_sta_reason']] : '';
            $new_data[] = $temp;
        }
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $new_data,
        );
        return $ret;
    }

    /**
     * 获取系统监控数据接口
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                     )
     * @return array
     */
    public function systemMonitor(array $param)
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $res = array();
        //计算queue_nums 排队数
        $res['queue_nums'] = $this->dbal->fetchColumn(
            'SELECT count(*) ' .
            'FROM win_call_queue ' .
            'WHERE vcc_id = :vcc_id AND queuer_sta = :queuer_sta ',
            array('vcc_id' => $vid, 'queuer_sta' => 0)
        );
        $res['ring_nums'] = $this->getCount(" vcc_id = $vid AND ag_sta=4 AND pho_sta=1 "); //ring_nums振铃数
        $res['call_nums'] = $this->getCount(" vcc_id = $vid AND ag_sta=4 AND pho_sta=2 "); //call_nums通话数
        $res['wait_nums'] = $this->getCount(" vcc_id = $vid AND ag_sta=5 "); //wait_nums事后整理数
        $res['ready_nums'] = $this->getCount(" vcc_id = $vid AND ag_sta=1 "); //ready_nums就绪数
        $res['busy_nums'] = $this->getCount(" vcc_id = $vid AND ag_sta=2 "); //busy_nums置忙数
        $max = max(array_values($res));
        $res['max'] = $max;
        $ret = array('code' => 200, 'message' => 'ok', 'data' => $res);
        return $ret;
    }

    /**
     * 获取ivr;用于监控坐席
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                         trunk_phones, //呼叫中心监控配置的中继号
     *                         monitor_queues_ids, //配置监控技能组的id
     *                     )
     * @return array
     */
    public function agentIvr(array $param)
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        //$trunk_phones = empty($param['trunk_phones']) ? array() : $param['trunk_phones'];
        $monitor_queues_ids = empty($param['monitor_queues_ids']) ? '' : $param['monitor_queues_ids'];
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        /*$trunkWhere = '';
        if (!empty($trunk_phones)) {
            //呼叫中心配置过来；
            $trunkStr = "'".implode("','", $trunk_phones)."'";
            $trunkWhere = " AND server_num IN ($trunkStr)";
            //查询 ivr进线数
            $system_day['ivr_num'] = $this->dbal->fetchColumn(
                'SELECT count(*) '.
                'FROM win_incdr '.
                'WHERE vcc_id = :vcc_id AND start_year = :start_year AND start_month = :start_month '.
                'AND start_day = :start_day '.$trunkWhere,
                array('vcc_id'=>$vid, 'start_year'=>date('Y'), 'start_month'=>date('m'), 'start_day'=>date('d'))
            );
        } else {
            //坐席监控过来
            $system_day = $this->dbal->fetchAssoc(
                'SELECT ivr_num,in_num,lost_num,nowdate '.
                'FROM rep_system_day '.
                'WHERE vcc_id = :vcc_id AND nowdate = :nowdate',
                array('vcc_id'=>$vid, 'nowdate'=>date('Y-m-d'))
            );
        }
        //ivr放弃数;
        $ivr_lost_num = $this->dbal->fetchColumn(
            'SELECT count(*) '.
            'FROM win_incdr '.
            'WHERE vcc_id = :vcc_id AND result = 1 AND start_year = :start_year AND start_month = :start_month '.
            'AND start_day = :start_day '.$trunkWhere,
            array('vcc_id'=>$vid, 'start_year'=>date('Y'), 'start_month'=>date('m'), 'start_day'=>date('d'))
        );

        //人工放弃数
        $queidStr = empty($monitor_queues_ids) ? '' : implode(',', $monitor_queues_ids);
        if (!empty($monitor_queues_ids)) {
            $res = $this->dbal->fetchAssoc(
                "SELECT SUM(in_num) as in_num,SUM(lost_num) as lost_num,nowdate
                FROM rep_queue_day WHERE vcc_id = :vcc_id AND nowdate = :nowdate AND queue_id IN ($queidStr)",
                array('vcc_id'=>$vid, 'nowdate'=>date('Y-m-d'))
            );

            $system_day['in_num'] = !empty($res) ? $res['in_num'] : 0;  //人工近线数
            $system_day['lost_num'] = !empty($res) ? $res['lost_num'] : 0; //人工放弃数
        }*/

        /** 计算技能组来电量、接通量、接通率 */
//        if (!empty($monitor_queues_ids)) {
//            $queidStr = empty($monitor_queues_ids) ? '' : implode(',', $monitor_queues_ids);
//            $queueDate = $this->dbal->fetchAssoc(
//                "SELECT SUM(conn_num) as conn_num,SUM(in_num) as in_num,SUM(lost4_num) as lost4_num,SUM(lost5_num) as lost5_num,nowdate
//                FROM rep_queue_day WHERE vcc_id = :vcc_id AND nowdate = :nowdate AND queue_id IN ($queidStr)",
//                array('vcc_id' => $vid, 'nowdate' => date('Y-m-d'))
//            );
//        } else {
//            $queueDate = $this->dbal->fetchAssoc(
//                "SELECT SUM(conn_num) as conn_num,SUM(in_num) as in_num,SUM(lost4_num) as lost4_num,SUM(lost5_num) as lost5_num,nowdate
//                FROM rep_queue_day WHERE vcc_id = :vcc_id AND nowdate = :nowdate",
//                array('vcc_id' => $vid, 'nowdate' => date('Y-m-d'))
//            );
//        }
        /*
        $must = array(array('match'=>array('vcc_id'=>$vid)));
        $esQuery = array(
            //'index'=>$this->container->getParameter('elasticsearch_index_name'),
            'index'=>'wincdr2',
            'type'=>'tmp_logs',
            'size'=>0,
            'body'=>array(
                'query'=>array(
                    'filtered'=>array(
                        'query'=>array(
                            'bool'=>array(
                            )
                        ),
                        'filter'=>array(
                            'range'=>array(
                                'call_time'=>array('gte'=>strtotime(date("Y-m-d")),'lte'=>strtotime(date("Y-m-d 23:59:59")))
                            ),
                        )
                    )
                ),
            )
        );
        //总呼入量
        $inNumMust = array(
            array('match'=>array('type'=>5)),
            array('match'=>array('log_type'=>'amount'))
        );

        $conNumMust = array(
            array('match'=>array('type'=>4)),
            array('match'=>array('ext_type'=>1)),
            array('match'=>array('log_type'=>'time'))
        );
        $hosts = $this->container->getParameter('elasticsearch_hosts');
        $client = new Client(array(
            'hosts' => $hosts,
            'logging' => false,
        ));
        //改成ES
        $queIds = array();
        if (!empty($monitor_queues_ids)) {
            foreach($monitor_queues_ids as $v) {
                $queIds[] = array('match'=>array('que_id'=>$v));
            }
        }
        if (!empty($queIds)) {
            $esQuery['body']['query']['filtered']['query']['bool']['should'] = $queIds;
            $esQuery['body']['query']['filtered']['query']['bool']['minimum_should_match'] = 1;
        }
        $esQuery['body']['query']['filtered']['query']['bool']['must'] = array_merge($inNumMust, $must);
        $esRes = $client->search($esQuery);
        $system_day['queue_in_num'] = isset($esRes['hits']['total']) ? $esRes['hits']['total'] : 0;
        $esQuery['body']['query']['filtered']['query']['bool']['must'] = array_merge($conNumMust, $must);
        $esRes = $client->search($esQuery);
        $system_day['conn_num'] = isset($esRes['hits']['total']) ? $esRes['hits']['total'] : 0;
        $system_day['conn_rate'] = $system_day['queue_in_num'] > 0 ? number_format($system_day['conn_num'] / $system_day['queue_in_num'] * 100, 2) . '%' : '0.00%';*/
//
//        $connNum = isset($queueDate['conn_num']) ? $queueDate['conn_num'] : 0;
//        $inNum = isset($queueDate['in_num']) ? $queueDate['in_num'] : 0;
//        $lost4Num = isset($queueDate['lost4_num']) ? $queueDate['lost4_num'] : 0;
//        $lost5Num = isset($queueDate['lost5_num']) ? $queueDate['lost5_num'] : 0;
//        $system_day['conn_num'] = $connNum;//接通量
//        $system_day['queue_in_num'] = ($inNum - $lost4Num - $lost5Num) > 0 ? ($inNum - $lost4Num - $lost5Num) : 0; //技能组来电量
//        $system_day['conn_rate'] = $system_day['queue_in_num'] > 0 ? number_format($connNum / $system_day['queue_in_num'] * 100, 2) . '%' : '0.00%'; //接通率
        //如果没有就查询所有技能组
        if (empty($monitor_queues_ids)) {
            $queIds = $this->dbal->fetchAll("SELECT id FROM win_queue WHERE vcc_id = ? AND is_del = 0", array($vid));
            $monitor_queues_ids = array_column($queIds, 'id');
        }
        $system_day['queue_in_num'] = 0;
        $system_day['conn_num'] = 0;
        foreach ($monitor_queues_ids as $qid) {
            $rhkey = sprintf('queue:%s:%s', $qid, date('Y-m-d'));
            $data = $this->container->get("snc_redis.monitor_client")->hgetall($rhkey);
            $queInNum = !empty($data['queueTotalNum']) ? (int) $data['queueTotalNum'] : 0;
            $connNum = !empty($data['inboundConnNum']) ? (int) $data['inboundConnNum'] : 0;
            $system_day['queue_in_num'] += $queInNum;
            $system_day['conn_num'] += $connNum;
        }
        $system_day['conn_rate'] = $system_day['queue_in_num'] > 0 ? number_format($system_day['conn_num'] / $system_day['queue_in_num'] * 100, 2) . '%' : '0.00%';
        //排队数
        $queue = $this->dbal->fetchColumn(
            'SELECT count(*) ' .
            'FROM win_call_queue ' .
            'WHERE vcc_id = :vcc_id ' . (empty($queidStr) ? '' : " AND que_id IN ($queidStr)"),
            array('vcc_id' => $vid)
        );

        $conn_num = $config_number = $this->dbal->fetchColumn(
            'SELECT conn_num ' .
            'FROM cc_ccod_configs ' .
            'WHERE vcc_id = :vcc_id ',
            array('vcc_id' => $vid)
        );
        if (empty($conn_num)) {
            $configs = array(15);
        } else {
            $configs = explode(',', $conn_num);
        }
        //坐席监控查rep_system_day,呼叫中心监控查询 rep_queue_day;]
//        $queidStr = empty($queidStr) ? '' : " AND queue_id IN ($queidStr)";
//        $table = empty($queidStr) ? 'rep_system_day' : 'rep_queue_day';
        if (empty($queidStr)) {
            $table = 'rep_system_day';
            $select = "conn_num,conn5_num,conn15_num,conn10_num,conn20_num,conn30_num ";
            $queidStr = '';
        } else {
            //从技能组中统计需要求各个技能组的；
            $select = "sum(conn_num) as conn_num,sum(conn5_num) as conn5_num,
                       sum(conn15_num) as conn15_num, sum(conn10_num) as conn10_num, sum(conn20_num) as conn20_num,
                       sum(conn30_num) as conn30_num ";
            $table = 'rep_queue_day';
            $queidStr = " AND queue_id IN ($queidStr) group by vcc_id";
        }
        $result = $this->dbal->fetchAssoc(
            'SELECT ' . $select .
            'FROM  ' . $table .
            ' WHERE vcc_id = :vcc_id AND nowdate = :nowdate ' . $queidStr,
            array('vcc_id' => $vid, 'nowdate' => date('Y-m-d'))
        );
        /** 计算接通率 */
        foreach ($configs as $v) {
            if (!isset($result["conn" . $v . "_num"])) {
                $conn_num = 0;
            } else {
                $conn_num = $result["conn" . $v . "_num"] > $result['conn_num'] ?
                    $result['conn_num'] : $result["conn" . $v . "_num"];
            }
            $result['conn_rate' . $v] = empty($result['conn_num']) ?
                '0.00%' : number_format($conn_num / $result['conn_num'] * 100, 2) . '%';
        }
        //IVR进线数
        $result['ivr_num'] = empty($system_day['ivr_num']) ? 0 : $system_day['ivr_num'];
        //人工进线数
        $result['in_num'] = empty($system_day['in_num']) ? 0 : $system_day['in_num'];
        //IVR放弃数
        $result['ivr_lost_num'] = empty($ivr_lost_num) ? 0 : $ivr_lost_num;
        //人工放弃数
        $result['lost_num'] = empty($system_day['lost_num']) ? 0 : $system_day['lost_num'];
        //人工放弃率
        $result['lost_rate'] = empty($result['in_num']) ?
            '0.00%' : number_format($system_day['lost_num'] / $result['in_num'] * 100, 2) . '%';
        //排队数
        $result['queue'] = empty($queue) ? 0 : $queue;
        /** 技能组来电量 */
        $result['queue_in_num'] = empty($system_day['queue_in_num']) ? 0 : $system_day['queue_in_num'];
        /** 接通量 */
        $result['conn_num'] = empty($system_day['conn_num']) ? 0 : $system_day['conn_num'];
        /** 接通率 */
        $result['conn_rate'] = empty($system_day['conn_num']) ? '0.00%' : $system_day['conn_rate'];
        //配置数
        $result['config_conn_num'] = empty($config_number) ? 15 : $config_number;
        return array('code' => '200', 'message' => 'ok', 'data' => $result);
    }


    /**
     * 获取示忙的理由
     * @param array $param 参数，格式为
     *                     array(
     *                         vcc_code,//企业代码
     *                     )
     * @return array
     */
    public function getReason(array $param)
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $result = $this->dbal->fetchAll(
            'SELECT id,stat_reason ' .
            'FROM win_agstat_reason ' .
            'WHERE vcc_id = :vcc_id ',
            array('vcc_id' => $vid)
        );
        return array('code' => '200', 'message' => 'ok', 'data' => $result);
    }

    /**
     * 获取监控配置列表；
     * @param array $param
     * @return array|string
     */
    public function getMonitorConfList(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $addInfo = empty($param['info']) ? array() : $param['info'];
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $where = '';
        if (isset($addInfo['filter'])) {
            $where = isset($addInfo['filter']['keyword']) && !empty($addInfo['filter']['keyword']) ?
                "and w.ag_num like '%" . trim($addInfo['filter']['keyword']) . "%' " : '';
        }
        $count = $this->dbal->fetchColumn(
            'SELECT count(w.id) ' .
            'FROM cc_monitor_config c ' .
            'INNER JOIN win_agent w ' .
            'ON c.user_id = w.id AND w.is_del = 0 ' .
            'WHERE w.vcc_id = :vcc_id ' . $where,
            array('vcc_id' => $vid)
        );
        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'win_agent', $addInfo);
        $list = $this->dbal->fetchAll(
            'SELECT c.*,w.ag_num,w.ag_name ' .
            'FROM cc_monitor_config c ' .
            'INNER JOIN win_agent w ' .
            'ON c.user_id = w.id AND w.is_del = 0 ' .
            'WHERE w.vcc_id = :vcc_id ' . $where .
            'ORDER BY ' . $page['sort'] . ' ' . $page['order'] . ' LIMIT ' . $page['start'] . ',' . $page['limit'],
            array('vcc_id' => $vid)
        );

        //获取技能组；
        $queues = $this->dbal->fetchAll(
            "SELECT id,que_name FROM win_queue WHERE is_del = 0 AND vcc_id = :vcc_id",
            array('vcc_id' => $vid)
        );
        $queue = array();
        foreach ($queues as $que) {
            $queue[$que['id']] = $que['que_name'];
        }
        $resData = array();
        foreach ($list as $val) {
            $val['ag_name'] = $val['ag_num'] . " " . $val['ag_name'];
            if (!empty($val['monitor_queues'])) {
                $temp = explode(',', $val['monitor_queues']);
                $que = '';
                foreach ($temp as $v) {
                    $temp_str = isset($queue[$v]) ? $queue[$v] : "";
                    $que .= $temp_str . ',';
                }
                $val['monitor_queues'] = rtrim($que, ',');
            }
            if (!empty($val['separate_queues'])) {
                $temp = explode(',', $val['separate_queues']);
                $separate_que = '';
                foreach ($temp as $v) {
                    $temp_str = isset($queue[$v]) ? $queue[$v] : "";
                    $separate_que .= $temp_str . ',';
                }
                $val['separate_queues'] = rtrim($separate_que, ',');
            }
            $resData[] = $val;
        }
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'page' => $page['page'],
            'totalPage' => $page['totalPage'],
            'data' => $resData,
        );
        return $ret;
    }

    /**
     * 操作监控配置
     * @param array $param
     * @return array|string
     */
    public function actionMonitorConf(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $data['monitor_queues'] = empty($param['que']) ? '' : $param['que'];
        $data['separate_queues'] = empty($param['separate_que']) ? '' : $param['separate_que'];
        $data['if_monitor_ivr_info'] = empty($param['show_ivr']) ? '' : $param['show_ivr'];
        $data['trunk_phones'] = (empty($param['trunk']) || $data['if_monitor_ivr_info'] != 1) ? '' : $param['trunk'];
        $userId = empty($param['userId']) ? '' : $param['userId'];
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        if (empty($userId)) {
            return array("code" => '403', 'message' => '坐席不能为空');
        } else {
            $res = $this->container->get('icsoc_data.validator')->agentExist($vid, $userId);
            if (!$res) {
                return array("code" => '404', 'message' => '坐席不存在');
            }
        }
        $count = $this->dbal->fetchColumn(
            "SELECT count(*) FROM cc_monitor_config WHERE user_id = :user_id AND vcc_id = :vcc_id",
            array('user_id' => $userId, 'vcc_id' => $vid)
        );
        try {
            if ($count) {
                //更新
                $this->dbal->update("cc_monitor_config", $data, array('user_id' => $userId, 'vcc_id' => $vid));
                $message = "修改成功";
            } else {
                $data['user_id'] = $userId;
                $data['vcc_id'] = $vid;
                $this->dbal->insert("cc_monitor_config", $data);
                $message = "添加成功";
            }
            return array("code" => 200, "message" => $message);
        } catch (DBALException $e) {
            return array("code" => 404, "message" => "添加监控失败");
        }
    }

    /**
     * 删除监控配置；
     * @param array $param
     *                  array(
     *                         vcc_code,//企业代码
     *                         ids=>array(1,2,3)//需要删除的id;
     *                    )
     * @return array
     */
    public function deleteConf(array $param = array())
    {
        $vcc_code = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $arr = empty($param['ids']) ? array() : $param['ids'];

        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($arr) || !is_array($arr)) {
            return array('code' => 403, 'message' => 'ids格式不正确或为空');
        }
        //转整
        $temp = array();
        foreach ($arr as $v) {
            $value = (int)$v;
            if ($value == 0) {
                continue;
            }
            $temp[] = $value;
        }
        if (empty($temp)) {
            return array('code' => 403, 'message' => 'ids格式不正确或为空');
        }
        $temp = array_unique($temp);
        $str = implode(',', $temp);
        $this->dbal->beginTransaction();
        try {
            $this->dbal->executeQuery(
                "DELETE FROM cc_monitor_config WHERE vcc_id = :vid AND id IN ($str)",
                array('vid' => $vid)
            );
            $this->dbal->commit();
            $actionLogger = $this->container->get('icsoc_core.helper.logger');
            $logStr = $this->container->get('translator')
                ->trans('Delete the monitoring configuration %str%', array('%str%' => $str));
            $actionLogger->actionLog(ActionLogger::ACTION_DELETE, $logStr);
            return array('code' => 200, 'message' => '删除成功');
        } catch (DBALException $e) {
            $this->dbal->rollBack();
            return array('code' => 404, 'message' => '删除失败');
        }
    }

    /**
     * @param int $where
     * @return mixed
     * 获取不同条件的监控统计数据
     */
    private function getCount($where = 1)
    {
        $count = $this->dbal->fetchColumn(
            'SELECT count(*) ' .
            'FROM win_agmonitor WHERE ' . $where
        );
        return $count;
    }

    /**
     * @param array $trunk_phones 监控配置中继号
     * @param array $monitor_queues 监控配置技能组
     * @param $vcc_id
     * @return array
     */
    public function separateIvr(array $trunk_phones, array $monitor_queues, $vcc_id)
    {
        if (empty($monitor_queues)) {
            return array();
        }
        $trunkstr = implode(',', $trunk_phones);
        $questr = implode(',', $monitor_queues);
        /*//IVR进线数
        if (!empty($trunk_phones)) {
            $ivr_num = $this->dbal->fetchColumn(
                "SELECT count(*)
                FROM win_incdr
                WHERE server_num IN ($trunkstr) AND vcc_id = :vcc_id
                AND start_year = :date AND start_month = :month AND start_day = :day ",
                array('vcc_id'=>$vcc_id, 'date'=>date('Y'), 'month'=>date('m'),
                    'day'=>date('d'))
            );
        } else {
            $ivr_num = 0 ;
        }

        //IVR放弃数
        if (!empty($trunk_phones)) {
            $ivr_lost_num = $this->dbal->fetchColumn(
                "SELECT count(*)
                FROM win_incdr
                WHERE server_num IN ($trunkstr) AND vcc_id = :vcc_id
                AND start_year = :date AND start_month = :month AND start_day = :day AND result = :result ",
                array('vcc_id'=>$vcc_id, 'date'=>date('Y'), 'month'=>date('m'),
                    'day'=>date('d'), 'result'=>1)
            );
        } else {
            $ivr_lost_num = 0;
        }

        //人工进线数,放弃数
        if (!empty($monitor_queues)) {
            //$str = implode(',', $monitor_queues);
            $res = $this->dbal->fetchAll(
                "SELECT SUM(in_num) as in_num,SUM(lost_num) as lost_num,nowdate,queue_id FROM rep_queue_day
                WHERE vcc_id = :vcc_id AND nowdate = :nowdate AND queue_id IN ($questr) GROUP BY queue_id ",
                array('vcc_id'=>$vcc_id, 'nowdate'=>date('Y-m-d'))
            );
            $in_num = $lost_num = array();
            foreach ($res as $v) {
                $in_num[$v['queue_id']] = $v['in_num'];
                $lost_num[$v['queue_id']] = $v['lost_num'];
            }
        }*/

        //排队数
        if (!empty($monitor_queues)) {
            $res = $this->dbal->fetchAll(
                "SELECT count(*) as num, que_id
                FROM win_call_queue WHERE que_id IN ($questr) AND vcc_id = :vcc_id AND queuer_sta = :queuer_sta
                GROUP BY que_id",
                array('vcc_id' => $vcc_id, 'queuer_sta' => 0)
            );
            $queue = array();
            foreach ($res as $val) {
                if (in_array($val['que_id'], $monitor_queues)) {
                    $queue[$val['que_id']] = $val['num'];
                }
            }
        } else {
            $queue = 0;
        }

        //获取配置接通率
        $conn_num = $this->dbal->fetchColumn(
            "SELECT conn_num FROM cc_ccod_configs WHERE vcc_id = :vcc_id",
            array('vcc_id' => $vcc_id)
        );
        if (!empty($conn_num)) {
            $configs = explode(',', $conn_num);
        } else {
            $configs = array(15);
        }

        /** 获取接通量数据 */
        $res = $this->dbal->fetchAll(
            "SELECT * FROM rep_queue_day WHERE vcc_id = :vcc_id AND nowdate = :nowdate GROUP BY queue_id",
            array('vcc_id' => $vcc_id, 'nowdate' => date('Y-m-d'))
        );

        foreach ($res as $value) {
            foreach ($configs as $v) {
                if (!isset($value["conn" . $v . "_num"])) {
                    $conn_num = 0;
                } else {
                    $conn_num = $value["conn" . $v . "_num"] > $value['conn_num'] ? $value['conn_num'] : $value["conn" . $v . "_num"];
                }
                $res[$value['queue_id']]['conn_rate' . $v] = empty($value['conn_num']) ?
                    '0.00%' : number_format($conn_num / $value['conn_num'] * 100, 2) . '%';
            }

            $inNum = $value['in_num'];
            $connNum[$value['queue_id']] = $value['conn_num'];
            $lost4Num = $value['lost4_num'];
            $lost5Num = $value['lost5_num'];
            $queueInNum[$value['queue_id']] = ($inNum - $lost4Num - $lost5Num) > 0 ? ($inNum - $lost4Num - $lost5Num) : 0;
            $connRate[$value['queue_id']] = $queueInNum[$value['queue_id']] > 0 ? number_format($value['conn_num'] / $queueInNum[$value['queue_id']] * 100, 2) . '%' : '0.00%';

        }

        $result = array();
        foreach ($monitor_queues as $val) {
            //IVR进线数
            $result[$val]['ivr_num'] = empty($ivr_num) ? 0 : $ivr_num;
            //IVR放弃数
            $result[$val]['ivr_lost_num'] = empty($ivr_lost_num) ? 0 : $ivr_lost_num;
            //人工进线数
            $result[$val]['in_num'] = empty($in_num[$val]) ? 0 : $in_num[$val];
            //人工放弃数
            $result[$val]['lost_num'] = empty($lost_num[$val]) ? 0 : $lost_num[$val];
            //人工放弃率
            $result[$val]['lost_rate'] = (empty($result[$val]) || empty($result[$val]['in_num'])) ?
                '0.00%' : number_format($result[$val]['lost_num'] / $result[$val]['in_num'] * 100, 2) . '%';
            //排队数
            $result[$val]['queue'] = empty($queue[$val]) ? 0 : $queue[$val];
            /** 技能组来电量 */
            $result[$val]['queue_in_num'] = empty($queueInNum[$val]) ? 0 : $queueInNum[$val];
            /** 接通量 */
            $result[$val]['conn_num'] = empty($connNum[$val]) ? 0 : $connNum[$val];
            /** 接通率 */
            $result[$val]['conn_rate_'] = empty($connRate[$val]) ? '0.00%' : $connRate[$val];
            foreach ($configs as $v) {
                $result[$val]['conn_rate' . $v] = empty($res[$val]['conn_rate' . $v]) ? '0.00%' : $res[$val]['conn_rate' . $v];
            }
        }
        return $result;
    }

    /**
     * 强制操作
     * @param int $vccId 企业id
     * @param int $code 操作类型（退出，致忙）
     * @param int $agId 坐席id
     * @return array
     */
    public function oprAgent($vccId, $code, $agId)
    {
        switch ($code) {
            case 4:
                $msg = "agexit($agId)";
                break;
            case 5:
                $msg = "agunbusy($agId)";
                break;
            case 6:
                $msg = "agbusy($agId)";
                break;
            default:
                $msg = '';
        }
        $res = $this->dbal->fetchAssoc(
            "SELECT id,ag_type FROM win_agent WHERE is_del = 0 AND id = :ag_id ",
            array('ag_id' => $agId)
        );
        if (!empty($res)) {
            if ($res['ag_type'] == 2) {
                return array('err' => true, 'msg' => '坐席是静态坐席，不能强制操作');
            }
        }
        $res = $this->agentOprate($msg, $vccId);
        if ($res === true) {
            return array('err' => false, 'msg' => '操作成功');
        } elseif ($res === false) {
            return array('err' => true, 'msg' => '连接通信服务器失败');
        } else {
            return $res;
        }
    }

    /**
     * 强制操作发送socket
     * @param $str
     * @param $vcc_id
     * @return array|bool
     */
    private function agentOprate($str, $vcc_id)
    {
        /** @var  $user \Icsoc\SecurityBundle\Entity\CcCcods */
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        //$winip = $this->container->getParameter("win_ip");
        $winip = $this->container->get('icsoc_core.common.class')->newGetWinIp();
        //$winip = $user->getWinIp();
        $port = $this->container->getParameter("win_socket_port");
        $logger = $this->container->get('logger');
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket === false) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            $message = "$vcc_id $str socket_create() failed: [$errorcode] $errormsg";
            $logger->debug('无法创建socket：【' . $errorcode . '】' . $message);
            return false;
        }

        $res = @socket_connect($socket, $winip, $port);
        if ($res === false) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            $message = "$vcc_id $str $winip socket_connect() failed: [$errorcode] $errormsg";
            $logger->debug('socket无法连接到【' . $winip . ':' . $port . '】：【' . $errorcode . '】' . $message);
            return false;
        }

        $res = @socket_write($socket, $str . "\r\n\r\n", strlen($str . "\r\n\r\n"));
        if ($res === false) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            $message = "$vcc_id $str socket_write() failed: [$errorcode] $errormsg";
            $logger->debug('socket发送数据失败：【' . $errorcode . '】' . $message);
            return false;
        }

        $responce = @socket_read($socket, 100);
        if ($responce === false) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            $message = "$vcc_id $str socket_read() failed: [$errorcode] $errormsg";
            $logger->debug('socket读取数据失败：【' . $errorcode . '】' . $message);
            return false;
        } elseif (strstr($responce, 'Success')) {
            return true;
        } else {
            $errname = $responce;
            $responce = explode("\r\n", $responce);
            $errcode = 'qzcz500';
            if (isset($responce[1])) {
                $errcodes = explode(":", $responce[1]);
                if (isset($errcodes[1])) {
                    switch (trim($errcodes[1])) {
                        case '1':
                            $errname = "坐席不存在";
                            break;
                        case '2':
                            $errname = "坐席未从页面登录(可能为静态坐席)";
                            break;
                        default:
                            $errname = "错误未定义，返回结果为【" . $errcodes[1] . "】";
                            break;
                    }
                    $errcode = $errcodes[1];
                }
            }
            $strs = "$vcc_id $str error: [$errcode] $errname";
            $logger->debug('强制操作失败：【' . $errcode . '】' . $strs);
            return array('err' => true, 'msg' => $errname);
        }
    }

    /**
     * 解析监控配置
     *
     * @param array $screen_info
     * @param array $data
     * @param int   $vccId
     * @return array
     */
    public function parseScreenInfo($screen_info, $data, $vccId)
    {
        $call_center = $que_center = $group_center = $agent_center = $rates = array();
        if (empty($screen_info)) {
            return array('code' => 400, 'message' => '该大屏监控信息未配置');
        }
        $screen_info = json_decode($screen_info, true);
        if (json_last_error()) {
            return array('code' => 402, 'message' => '大屏监控信息配置错误');
        }
        $call_center_param = $que_center_param = $group_center_param = array();

        //监控配置
        if (!empty($screen_info['mainFields']) && is_array($screen_info['mainFields'])) {
            $i = 0;
            foreach ($screen_info['mainFields'] as $key => $screen) {
                switch ($screen['type']) {
                    case 1:
                        //呼叫中心监控
                        $call_count = count($screen['fields']);
                        $items = array();
                        foreach ($screen['fields'] as $k => $val) {
                            if (!empty($data['is_set_reason']) && $val['id'] == 'busyTotalNum') {
                                $call_count = $call_count - 1;
                                //总示忙次数
                                foreach($data['data'] as $t=>$busy) {
                                    $backColor = $this->backgroudColor[$i];
                                    if (empty($val['style'])) {
                                        $screen['fields'][$k]['busy'][$t]['style'] = array("background"=>$backColor, "fontColor"=>"#ffffff", "fontSize"=>"28px");
                                        $i++;
                                    } else {
                                        $screen['fields'][$k]['busy'][$t]['style'] = array("background"=>$backColor, "fontColor"=>$val['style']['fontColor'], "fontSize"=>$val['style']['fontSize']);
                                        $i++;
                                    }
                                    $screen['fields'][$k]['busy'][$t]['id'] = 'busyTotalNum'.$busy['id'];
                                    $screen['fields'][$k]['busy'][$t]['name'] = $busy['stat_reason'].'次数';
                                    $items[] = 'busyTotalNum'.$busy['id'];
                                }
                                $call_count = count($data['data']) + $call_count;
                            } else {
                                if (empty($val['style'])) {
                                    $backColor = $this->backgroudColor[$i];
                                    $screen['fields'][$k]['style'] = array("background"=>$backColor,"fontColor"=>"#ffffff","fontSize"=>"28px");
                                    $i++;
                                }
                                $items[] = $val['id'];
                            }
                        }

                        $items = array_unique($items);
                        if (!empty($items)) {
                            sort($items);
                        }
                        $call_center_param = array('vcc_id' => $vccId, 'items' => $items);
                        $call_center['data'] = $this->splitArrayByData($call_count, $screen['fields'], $data['is_set_reason']);
                        $call_center['fields'] = $screen['fields'];
                        break;
                    case 2:
                        //技能组话务监控
                        $items = array();
                        $que_count = count($screen['fields']);
                        foreach ($screen['fields'] as $k => $val) {
                            if (empty($val['style'])) {
                                $backColor = $this->backgroudColor[$i];
                                $screen['fields'][$k]['style'] = array("background"=>$backColor,"fontColor"=>"#ffffff","fontSize"=>"28px");
                                $i++;
                            }

                            if ($val['id'] == 'ivrInboundTotalNum') {
                                if (!empty($val['phones'])) {
                                    $phones = $val['phones'];
                                    $que_center_param['phones'] = $phones;
                                }
                            }
                            if (!empty($val['id'])) {
                                $items[] = $val['id'];
                            }
                        }

                        $items = array_unique($items);
                        if (!empty($items)) {
                            sort($items);
                        }
                        $que_center_param['vcc_id'] = $vccId;
                        $que_center_param['items'] = $items;
                        $que_center['data'] = $this->splitArrayByData($que_count, $screen['fields'], $data['is_set_reason']);
                        $que_center['fields'] = $screen['fields'];
                        break;
                    case 3:
                        $items = array();
                        $group_count = count($screen['fields']);
                        foreach ($screen['fields'] as $k => $val) {
                            if (!empty($data['is_set_reason']) && $val['id'] == 'busyRate') {
                                //示忙占比
                                foreach($data['data'] as $t=>$busy) {
                                    $backColor = $this->backgroudColor[$i];
                                    if (empty($val['style'])) {
                                        $screen['fields'][$k]['busy'][$t]['style'] = array("background"=>$backColor, "fontColor"=>"#ffffff", "fontSize"=>"28px");
                                        $i++;
                                    } else {
                                        $screen['fields'][$k]['busy'][$t]['style'] = array("background"=>$backColor, "fontColor"=>$val['style']['fontColor'], "fontSize"=>$val['style']['fontSize']);
                                        $i++;
                                    }
                                    $screen['fields'][$k]['busy'][$t]['id'] = 'busyRate'.$busy['id'];
                                    $screen['fields'][$k]['busy'][$t]['name'] = $busy['stat_reason'].'占比';
                                    $items[] = 'busyRate'.$busy['id'];
                                }
                                $group_count = $group_count + count($data['data']) - 1;

                            } elseif (!empty($data['is_set_reason']) && $val['id'] == 'busyTotalNum') {
                                //总示忙次数
                                foreach($data['data'] as $t=>$busy) {
                                    $backColor = $this->backgroudColor[$i];
                                    if (empty($val['style'])) {
                                        $screen['fields'][$k]['busy'][$t]['style'] = array("background"=>$backColor, "fontColor"=>"#ffffff", "fontSize"=>"28px");
                                        $i++;
                                    } else {
                                        $screen['fields'][$k]['busy'][$t]['style'] = array("background"=>$backColor, "fontColor"=>$val['style']['fontColor'], "fontSize"=>$val['style']['fontSize']);
                                        $i++;
                                    }
                                    $screen['fields'][$k]['busy'][$t]['id'] = 'busyTotalNum'.$busy['id'];
                                    $screen['fields'][$k]['busy'][$t]['name'] = $busy['stat_reason'].'次数';
                                    $items[] = 'busyTotalNum'.$busy['id'];
                                }
                                $group_count = $group_count + count($data['data']) - 1;
                            } else {
                                if (empty($val['style'])) {
                                    $backColor = $this->backgroudColor[$i];
                                    $screen['fields'][$k]['style'] = array("background"=>$backColor,"fontColor"=>"#ffffff","fontSize"=>"28px");
                                    $i++;
                                }
                                $items[] = $val['id'];
                            }
                        }

                        $items = array_unique($items);
                        if (!empty($items)) {
                            sort($items);
                        }
                        $group_center_param = array('vcc_id' => $vccId, 'items' => $items);
                        //业务组话务监控
                        $group_center['data'] = $this->splitArrayByData($group_count, $screen['fields'], $data['is_set_reason']);
                        $group_center['fields'] = $screen['fields'];
                        break;
                }
            }
        }

        $agentLimit = $agentStyle =  array();
        //坐席监控配置
        if (!empty($screen_info['agent']) && is_array($screen_info)) {
            $agent_center = $screen_info['agent'];
            foreach ($screen_info['agent'] as $key => $val) {
                if (is_array($val) && !empty($val)) {
                    if ($key == 'busy') {
                        if (isset($screen_info['agent']['busy']['if_hasreason']) && $screen_info['agent']['busy']['if_hasreason'] == 1) {
                            //有置忙原因
                            $nowBusyIds = array();
                            if (!empty($val['busy_data']) && is_array($val['busy_data'])) {
                                foreach ($val['busy_data'] as $k => $v) {
                                    if (isset($v['id'])) {
                                        if ($v['id'] != 2) {
                                            $keyitem = "2".$v['id'];
                                        } else {
                                            $keyitem = $v['id'];
                                        }
                                        $nowBusyIds[] = $v['id'];
                                        $agentLimit[$keyitem] = empty($v['threshold']) ? 0 : $v['threshold'];
                                        if (isset($v['style'])) {
                                            $agentStyle[$keyitem] = $v['style'];
                                        }
                                    }
                                }
                            }

                            if (!empty($data['data'])) {
                                foreach($data['data'] as $busy) {
                                    if (!in_array($busy['id'], $nowBusyIds) && $busy['id'] != 2) {
                                        $agentStyle['2'.$busy['id']] = array("background" => "#FF0000", "fontColor" => '#FFFFFF', "fontSize" => "12px");
                                    }
                                }
                            }
                        }
                    } else {
                        switch ($key) {
                            case 'ready':
                                //就绪
                                $agentLimit[1] = empty($val['threshold']) ? 0 : $val['threshold'];
                                $agentStyle[1] = array("background" => $val['background'], "fontColor" => $val['fontColor'], "fontSize" => $val['fontSize']);
                                break;
                            case 'ring':
                                //振铃
                                $agentLimit[41] = empty($val['threshold']) ? 0 : $val['threshold'];
                                $agentStyle[41] = array("background" => $val['background'], "fontColor" => $val['fontColor'], "fontSize" => $val['fontSize']);
                                break;
                            case 'call':
                                //通话
                                $agentLimit[42] = empty($val['threshold']) ? 0 : $val['threshold'];
                                $agentStyle[42] = array("background" => $val['background'], "fontColor" => $val['fontColor'], "fontSize" => $val['fontSize']);
                                break;
                            case 'rest':
                                //事后处理
                                $agentLimit[5] = empty($val['threshold']) ? 0 : $val['threshold'];
                                $agentStyle[5] = array("background" => $val['background'], "fontColor" => $val['fontColor'], "fontSize" => $val['fontSize']);
                                break;
                        }
                    }
                }
            }
            if (empty($agentStyle[2])) {
                $agentStyle[2] = array("background" => "#FF0000", "fontColor" => '#FFFFFF', "fontSize" => "12px");
            }
            if (!empty($screen_info['agent']['busy']['if_hasreason']) && $screen_info['agent']['busy']['if_hasreason'] == 1) {
                //有置忙原因
                $count = count($screen_info['agent']['busy']['busy_data']) == 0 ? 0 : count($screen_info['agent']['busy']['busy_data']);
                $count = $count + 4;
            } else {
                $count = 5;
            }
            $rate = bcdiv(100, $count, 3)."%";
        } else {
            $rate = '0%';
        }
        $rates['agent_rate'] = $rate;

        return array('code' => 200, 'message' => 'ok', 'data' => array('call_center' => $call_center, 'que_center' => $que_center, 'group_center' => $group_center, 'agent_center' => $agent_center, 'rates' => $rates, 'agentLimit' => $agentLimit, 'agentStyle' => $agentStyle, 'call_center_param' => $call_center_param, 'que_center_param' => $que_center_param, 'group_center_param' => $group_center_param));
    }

    /**
     * 分列数组
     *
     * @param $total
     * @param $data
     * @param $is_set_reason
     * @return array
     */
    public function splitArrayByData($total, $data, $is_set_reason)
    {
        $real_data = array();
        //对data进行变换
        $responce = array();
        if ($total == 0) {
            return $responce;
        }
        $j = 0;
        foreach ($data as $key => $val) {
            if (!empty($is_set_reason) && ($val['id'] == 'busyTotalNum' || $val['id'] == 'busyRate')) {
                //设置了置忙原因
                foreach ($val['busy'] as $k => $busy) {
                    $busy['len'] = mb_strlen($busy['name'], 'utf-8');
                    $real_data[$j] = $busy;
                    $j++;
                }
            } else {
                $val['len'] = mb_strlen($val['name'], 'utf-8');
                $real_data[$j] = $val;
                $j++;
            }
        }
        $i = $tmptotal = 0;
        foreach ($real_data as $key => $item) {
            $rate = bcmul(3, $item['len']);
            $tmptotal += $rate;
            if ($tmptotal > 100) {
                $i++;
                $tmptotal = 0;
            }
            $responce[$i][$key] = $item;
        }

        foreach ($responce as $itemkey => $itemvalue) {
            $totalkey = 0;
            foreach ($itemvalue as $item) {
                $totalkey += $item['len'];
            }

            $totalRate = 100;
            $index = 0;
            foreach ($itemvalue as $k => $item) {
                $len = mb_strlen($item['name'], 'utf-8');
                if ($index == count($itemvalue)-1) {
                    $responce[$itemkey][$k]['rate'] = $totalRate.'%';
                } else {
                    $totalRate = bcsub($totalRate, bcmul(bcdiv($len, $totalkey, 3), 100, 3), 3) ;
                    $responce[$itemkey][$k]['rate'] = bcmul(bcdiv($len, $totalkey, 3), 100, 3).'%';
                }
                $index++;
            }
        }

        return $responce;
    }

    /**
     * 返回换行的比例
     *
     * @param $total
     * @return array
     */
    public function getRateByTotalNum($total)
    {
        $rate = array();
        if ($total == 0) {
            $rate[0] = '0%';
            return $rate;
        }
        $i = 0;
        while ($total > 0) {
            if ($total > 6) {
                $total = $total - 6;
                $rate[$i] = bcdiv(100, 6, 3).'%';
            } else {
                $rate[$i] = bcdiv(100, $total, 3).'%';
                $total = 0;
            }
            $i++;
        }
        return $rate;
    }

    /**
     * 获取管理数据
     * @param int $role_id
     * @param int $user_id
     * @return array
     */
    public function getRoleDataInfo($role_id, $user_id)
    {
        $result = array(
            "user_type" => 2,
            "data" => array()
        );
        if (empty($role_id)) {
            return $result;
        }
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $vcc_id = $user->getVccId();//企业Id
        //根据role_id查找user_type,user_queues
        $roles = $conn->fetchAssoc("SELECT user_type,user_queues FROM cc_roles WHERE vcc_id = ? AND role_id = ? LIMIT 1", array($vcc_id, $role_id));

        //0不限 1技能组 2坐席 3业务组
        $user_type = empty($roles['user_type']) ? 0 : $roles['user_type'];
        //所分配的数据权限
        $user_queues = empty($roles['user_queues']) ? "" : $roles['user_queues'];
        $data = array();
        if (in_array($user_type, array(1, 3)) && !empty($user_queues)) {
            //业务组，技能组
            $sql = "";
            switch($user_type)
            {
                case '1':
                    //技能组
                    if (is_numeric($user_id) && !empty($user_id)) {
                        //判断user_queues中是否存在-1
                        $queuearray = explode(',', $user_queues);
                        $queues = $queuearray;
                        foreach ($queuearray as $queId) {
                            if ($queId == '-1') {
                                $tmpques = array();
                                //查询登陆坐席的技能组
                                $agqueues = $conn->fetchAll("SELECT que_id FROM win_agqu WHERE ag_id = :ag_id", array('ag_id' => $user_id));
                                if (!empty($agqueues) && is_array($agqueues)) {
                                    $tmpques = array_column($agqueues, 'que_id');
                                }
                                $queues = array_merge($queuearray, $tmpques);
                            }
                        }
                        $queues = array_unique($queues);
                        $user_queues = implode(',', $queues);
                    }
                    $sql = "SELECT id,que_name FROM win_queue WHERE id IN ($user_queues) AND vcc_id = ? AND is_del = 0";
                    break;
                case '3':
                    //业务组
                    $sql = "SELECT group_id,group_name FROM win_group WHERE group_id IN ($user_queues) AND vcc_id = ? AND is_del = 0";
                    break;
            }
            $data = $conn->fetchAll($sql, array($vcc_id));
        }
        $result['user_type'] = $user_type;
        $result['data'] = $data;
        return $result;
    }

    /**
     * 获取企业所有的业务组或技能组
     *
     * @param $type
     * @return array
     */
    public function getAllDataInfo($type)
    {
        $result = array();
        $type = empty($type) ? 1 : $type;//默认按技能组
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $vcc_id = $user->getVccId();//企业Id
        $sql = "";
        $conn = $this->container->get('doctrine.dbal.default_connection');
        switch($type)
        {
            case 1:
                $sql = "SELECT id,que_name FROM win_queue WHERE vcc_id = ? AND is_del = 0";
                break;
            case 2:
                $sql = "SELECT group_id,group_name FROM win_group WHERE vcc_id = ? AND is_del = 0";
                break;
        }
        $result = $conn->fetchAll($sql, array($vcc_id));
        return $result;
    }

    /**
     * 获取该企业是否设置了置忙原因项
     *
     * @return array
     */
    public function getBusyReason()
    {
        $result = array();
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        $vcc_id = $user->getVccId();
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $busy_reason = $conn->fetchAll("SELECT id,stat_reason FROM win_agstat_reason WHERE vcc_id = ?", array($vcc_id));
        if (empty($busy_reason)) {
            $result['is_set_reason'] = 0;
        } else {
            $result['is_set_reason'] = 1;
            $result['data'] = $busy_reason;
        }
        return $result;
    }

    /**
     * 通过技能组id获取所有坐席及技能组下的坐席
     *
     * @param $que_id
     * @return array
     */
    public function getAgentByQueId($que_id)
    {
        $agents = $agent = array();
        if (empty($que_id)) {
            return array('agent'=>$agent, 'agents'=>$agents);
        }
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $que_id = explode(',', $que_id);
        foreach ($que_id as $val) {
            if (!empty($val)) {
                $agentArray = $conn->fetchAll("SELECT ag_id FROM win_agqu WHERE que_id = ?", array($val));
                $agents[$val] = array();
                foreach ($agentArray as $array) {
                    if (!empty($array['ag_id'])) {
                        $agent[] = $array['ag_id'];
                    }
                    if (!empty($array['ag_id'])) {
                        $agents[$val][] = $array['ag_id'];
                    }
                }
                $agents[$val] = array_unique($agents[$val]);
            }
        }
        $agent = array_unique($agent);
        return array('agent'=>$agent, 'agents'=>$agents);
    }

    /**
     * 通过业务组id获取所有坐席及业务组下的坐席
     *
     * @param $group_id
     * @return array
     */
    public function getAgentByGroupId($group_id)
    {
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        $vcc_id = $user->getVccId();
        $agents = $agent = array();
        if (empty($group_id)) {
            return array('agent'=>$agent, 'agents'=>$agents);
        }
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $group_id = explode(',', $group_id);
        foreach ($group_id as $val) {
            if (!empty($val)) {
                $agentArray = $conn->fetchAll("SELECT id FROM win_agent WHERE vcc_id = ? AND group_id = ? AND is_del = ?", array($vcc_id, $val, 0));
                $agents[$val] = array();
                foreach ($agentArray as $array) {
                    if (!empty($array['id'])) {
                        $agent[] = $array['id'];
                    }
                    if (!empty($array['id'])) {
                        $agents[$val][] = $array['id'];
                    }
                }
                $agents[$val] = array_unique($agents[$val]);
            }
        }
        $agent = array_unique($agent);
        return array('agent'=>$agent, 'agents'=>$agents);
    }

    /**
     * 获取角色名称
     *
     * @param $role_id
     * @return string
     */
    public function getRoleNameById($role_id)
    {
        $role_name = "";
        if (empty($role_id)) {
            return $role_name;
        }
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        $vcc_id = $user->getVccId();
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $role_name = $conn->fetchColumn("SELECT `name` FROM `cc_roles` WHERE vcc_id = ? AND role_id = ?", array($vcc_id, $role_id), 0);
        return $role_name;
    }

    /**
     * 获取监控配置详情
     *
     * @param $screen_info
     * @return array
     */
    public function getParsedInfo($screen_info)
    {
        $info = array(
            "call_center" => array(),
            "que_center" => array(),
            "group_center" => array(),
            "agent_center" => "不显示"
        );
        //字符串为空
        if (empty($screen_info)) {
            return $info;
        }
        $screen_info = json_decode($screen_info, true);
        //json解析错误
        if (json_last_error()) {
            return $info;
        }
        //无任何配置信息
        if (!empty($screen_info['mainFields']) && is_array($screen_info['mainFields'])) {
            //循环配置信息
            foreach ($screen_info['mainFields'] as $key => $val) {
                switch($val['type']) {
                    case '1':
                        //call_center内容
                        if (!empty($val['fields']) && is_array($val['fields'])) {
                            foreach ($val['fields'] as $k => $fields) {
                                if ($fields['id'] == 'inboundConnInXSecsNum' || $fields['id'] == 'inboundConnInXSecsRate' || $fields['id'] == 'inboundAbandonInXSecsNum' || $fields['id'] == 'inboundAbandonInXSecsRate') {
                                    if (empty($fields['paramName']) || !is_array($fields['paramName'])) {
                                        $info['call_center'][$fields['id'] . '10'] = "10秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                        $info['call_center'][$fields['id'] . '20'] = "20秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                        $info['call_center'][$fields['id'] . '30'] = "30秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                    } else {
                                        foreach ($fields['paramName'] as $paramKey => $paramName) {
                                            $info['call_center'][$paramName['id']] = $paramName['name'];
                                        }
                                    }
                                } else {
                                    $info['call_center'][$fields['id']] = $fields['name'];
                                }
                            }
                        }
                        break;
                    case '2':
                        //que_center内容
                        if (!empty($val['fields']) && is_array($val['fields'])) {
                            foreach ($val['fields'] as $k => $fields) {
                                if ($fields['id'] == 'inboundConnInXSecsNum' || $fields['id'] == 'inboundConnInXSecsRate' || $fields['id'] == 'inboundAbandonInXSecsNum' || $fields['id'] == 'inboundAbandonInXSecsRate') {
                                    if (empty($fields['paramName']) || !is_array($fields['paramName'])) {
                                        $info['que_center'][$fields['id'] . '10'] = "10秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                        $info['que_center'][$fields['id'] . '20'] = "20秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                        $info['que_center'][$fields['id'] . '30'] = "30秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                    } else {
                                        foreach ($fields['paramName'] as $paramKey => $paramName) {
                                            $info['que_center'][$paramName['id']] = $paramName['name'];
                                        }
                                    }
                                } else {
                                    $info['que_center'][$fields['id']] = $fields['name'];
                                }
                            }
                        }
                        break;
                    case '3':
                        //group_center内容
                        if (!empty($val['fields']) && is_array($val['fields'])) {
                            foreach ($val['fields'] as $k => $fields) {
                                if ($fields['id'] == 'inboundConnInXSecsNum' || $fields['id'] == 'inboundConnInXSecsRate' || $fields['id'] == 'inboundAbandonInXSecsNum' || $fields['id'] == 'inboundAbandonInXSecsRate') {
                                    if (empty($fields['paramName']) || !is_array($fields['paramName'])) {
                                        $info['group_center'][$fields['id'] . '10'] = "10秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                        $info['group_center'][$fields['id'] . '20'] = "20秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                        $info['group_center'][$fields['id'] . '30'] = "30秒" . str_replace(array('inboundConnInXSecsNum', 'inboundConnInXSecsRate', 'inboundAbandonInXSecsNum', 'inboundAbandonInXSecsRate'), array('接通量', '接通率', '放弃量', '放弃率'), $fields['id']);
                                    } else {
                                        foreach ($fields['paramName'] as $paramKey => $paramName) {
                                            $info['group_center'][$paramName['id']] = $paramName['name'];
                                        }
                                    }
                                } else {
                                    $info['group_center'][$fields['id']] = $fields['name'];
                                }
                            }
                        }
                        break;
                }
            }
        }
        //坐席配置信息
        if (!empty($screen_info['agent']) && is_array($screen_info['agent'])) {
            //坐席配置
            if ($screen_info['agent']['is_show'] == 1) {
                //显示
                $info['agent_center'] = "显示";
            }
        }
        return $info;
    }

    /**
     * 根据类型获取不同的Item
     *
     * @param $role_id
     * @param int $type
     * @return array
     */
    public function getCustomReportIndex($role_id, $type=1)
    {
        $result = array();
        if (empty($role_id)) {
            return $result;
        }
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        $vcc_id = $user->getVccId();
        //根据角色获取数据指标
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $report_config = $conn->fetchColumn("SELECT report_config FROM cc_roles WHERE vcc_id = ? AND role_id = ? LIMIT 1", array($vcc_id, $role_id), 0);
        if (empty($report_config)) {
            return $result;
        }
        $report_config = json_decode($report_config, true);
        if (json_last_error()) {
            return $result;
        }
        //分析type
        switch($type)
        {
            case '1':
                //呼叫中心指标
                if (!empty($report_config['system'])) {
                    $result = $this->getIndexByArray($report_config['system']);
                }
                break;
            case '2':
                if (!empty($report_config['queue'])) {
                    $result = $this->getIndexByArray($report_config['queue']);
                }
                break;
            case '3':
                if (!empty($report_config['group'])) {
                    $result = $this->getIndexByArray($report_config['group']);
                }
                break;
        }
        return $result;
    }

    /**
     * 获取唯一的item
     *
     * @param $array
     * @return array
     */
    public function getIndexByArray($array)
    {
        $result = array();
        if (empty($array) || !is_array($array)) {
            return $result;
        }
        if (!empty($array['calculateItems']) && is_array($array['calculateItems'])) {
            foreach ($array['calculateItems'] as $key => $val) {
                $keysItem = array();
                //分子、分母
                if (!empty($val['numerator']['plus'])) {
                    //加法值是否存在
                    $keysItem = array_merge($keysItem, $val['numerator']['plus']);
                }
                if (!empty($val['numerator']['minus'])) {
                    //减法值是否存在
                    $keysItem = array_merge($keysItem, $val['numerator']['minus']);
                }
                if (!empty($val['denominator']['plus'])) {
                    $keysItem = array_merge($keysItem, $val['denominator']['plus']);
                }
                if (!empty($val['denominator']['minus'])) {
                    $keysItem = array_merge($keysItem, $val['denominator']['minus']);
                }
                $keysItem = array_unique($keysItem);
                $result[$key] = $keysItem;
            }
        }
        return $result;
    }

    /**
     * 根据技能组ID获取业务组信息
     * @param int $queId
     * @param int $vccId
     * @return array
     */
    public function getGroupInfoByqueId($queId, $vccId)
    {
        if (empty($queId)) {
            return array("group_ids" => array(), "group_info" => array());
        }
        try {
            $conn = $this->container->get("doctrine.dbal.default_connection");
            $belongGroup = $conn->fetchColumn("SELECT group_belong FROM win_queue WHERE id = :id AND vcc_id = :vcc_id", array('id' => $queId, 'vcc_id' => $vccId), 0);
            $groupIds = $groups = array();
            if (!empty($belongGroup)) {
                $groups = $conn->fetchAll("SELECT group_id,group_name FROM win_group WHERE group_id IN ($belongGroup)");
                if (!empty($groups) && is_array($groups)) {
                    foreach ($groups as $group) {
                        $groupIds[] = $group['group_id'];
                    }
                }
            }
            $groupIds = array_unique($groupIds);

            return array("group_ids" => $groupIds, "group_info" => $groups);
        } catch (\Exception $e) {
            $this->container->get("logger")->error(sprintf("根据技能组ID获取所属业务组信息异常, 异常信息为[%s] .", $e->getMessage()));
        }
    }

    public function getAllAgentsData($vccId)
    {
        if (empty($vccId)) {
            return array();
        }
        $conn = $this->container->get("doctrine.dbal.default_connection");
        /** 查询出未删除的所有该企业的坐席 */
        $agent = $conn->fetchAll("SELECT id,ag_name FROM win_agent WHERE vcc_id = ? AND is_del = ?", array($vccId, 0));
    }
}
